package com.fagu.openerp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.log4j.Logger;

public class DB {
	
	private Properties properties = new Properties();
	
	private final String DB_PROPERTIES_PATH = "/com/fagu/openerp/properties/DB.properties";
	
	private String host, dbname, user, password;
	private int port;
	
	private Logger log = Logger.getLogger(getClass().getName());
	
	private Connection con;  
	
	public DB() {
		init();
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException e) {
			log.error(e.getMessage());
		}
		connect();
	}
	
	private void init() {
		properties = MyProperties.getProperties(DB_PROPERTIES_PATH);
		
		host = properties.get("HOST").toString();
		port = Integer.parseInt(properties.get("PORT").toString());
		dbname = properties.get("DBNAME").toString();
		user = properties.get("USER").toString();
		password = properties.get("PASSWORD").toString();
	}
	
	public void connect() {
		connect(host, port, dbname, user, password);
	}
	
	public void connect(String host, int port, String dbname, String username, String password){
		String connectionURL = "jdbc:postgresql://" + host + ":" + port + "/" + dbname;
		
		log.info(connectionURL);
		
		try {
			con = DriverManager.getConnection(connectionURL, username, password);
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
	}
	
	public ResultSet getData(String sql) {
		ResultSet rs = null;
		try {
			Statement stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		
		return rs;
	}

}
